﻿using System;
using System.ComponentModel;
using System.Reflection;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using zijian666.Core;

namespace zijian666.WebApi
{
    public partial class WebApiOptions
    {

        /// <summary>
        /// 绑定配置类
        /// </summary>
        /// <param name="key">配置前缀</param>
        /// <param name="configType">配置类</param>
        public void BindConfigurationSection(string key, Type configType)
        {
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (configType is null)
            {
                return;
            }

            //_services.ConfigureOptions(configType);
            _services.AddSingleton(configType, p =>
            {
                var configInstance = ActivatorUtilities.CreateInstance(p, configType);
                var configuration = p.GetService<IConfiguration>();
                configuration?.Bind(key, configInstance);
                return configInstance;
            });
        }

        /// <summary>
        /// 绑定指定配置类，配置前缀为 <seealso cref="CategoryAttribute.Category"/> 或类名(未标记特性时)
        /// </summary>
        /// <param name="configType"></param>
        public void BindConfigurationSection(Type configType)
        {
            if (configType is null)
            {
                return;
            }

            var attr = configType.GetCustomAttribute<CategoryAttribute>();
            var key = attr?.Category ?? configType.Name;
            BindConfigurationSection(key, configType);
        }



        /// <summary>
        /// 绑定所有被标记为<seealso cref="CategoryAttribute"/>的配置类
        /// </summary>
        public void BindConfigurationSection()
        {
            foreach (var (type, attr) in AssemblyResolver.Default.GetTypesWithAttribute<CategoryAttribute>())
            {
                BindConfigurationSection(attr.Category, type);
            }
        }
    }
}
